using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Microsoft.MediaCenter.UI;
using Microsoft.MediaCenter.Hosting;
using Level65.WMVHelper;
using Level65.ClipShow;
using System.Threading;

namespace ClipShow
{
    public class DefaultCodeBehind : CoreUICodeBehind 
    {
        private bool _haveLibraries = false;
        private Thread _thread;

        public DefaultCodeBehind()
        {
            Storage st = new Storage();
            _haveLibraries = ((st.GetMediaLibraryCount() > 0));
            base.BuildLibraryOptions(true, true);
            BuildCommandBar();

            // Build filters
            ArrayListDataSet tempFilters = new ArrayListDataSet();

            //foreach (ClipShowContent cm in this.MediaLibraries.Options)

            tempFilters.Add(new FilterBarItem("by visual tag", "view my media thumbnails by tag", TileViewTypes.MediaItems));
            if (this.TagsExist)
            {
                tempFilters.Add(new FilterBarItem("by tag", "view my media by tags", TileViewTypes.Topics));
            }
            tempFilters.Add(new FilterBarItem("by date", "view my media items by date",TileViewTypes.Timeline));

            // Check for playlists
            if (st.GetMyCollections().Count > 0)
            {
                tempFilters.Add(new FilterBarItem("my playlists", "view my playlists", TileViewTypes.Playlists));
            }

            ClipShowContent cm = st.GetSnagCollection();
            if (cm.MediaItems.Count > 0)
            {
                tempFilters.Add(new FilterBarItem("my snags", "view my snagged clips", TileViewTypes.Snags));
            }
            
            base.AddMediaFilterItems(tempFilters);

            //// Check for thumbnail work
            _thread = new Thread(new ThreadStart(StartThumbnailBuild));
            _thread.Name = "mce_clipShow_ThumbBuildThread";
            _thread.IsBackground = true;
            _thread.Priority = ThreadPriority.Normal;
            _thread.Start();
        }

        #region Private subroutines
        private void StartThumbnailBuild()
        {
            Reader wmv = new Reader();
            wmv.BuildThumbnails();
        }

        private void BuildCommandBar()
        {
            ArrayListDataSet tempCommandBarItems = new ArrayListDataSet();
            tempCommandBarItems.Add(new CommandBarItem("Shuffle All", "shuffle my media and start a clip show"));
            tempCommandBarItems.Add(new CommandBarItem("Create Playlist", "create a custom playlist from my media"));
            tempCommandBarItems.Add(new CommandBarItem("About", "about clipShow"));
            base.AddCommandBarItems(tempCommandBarItems);
        }
        #endregion

        #region Methods

        public MainCodeBehind ResultPageWithChannelFromTimeline 
        {
            get
            {
                PreviewChannelItem ci = (PreviewChannelItem)base.MediaLibraryItems.Options[base.CurrentTileIndex];
                MainCodeBehind cb = new MainCodeBehind();
                try
                {
                    ClipCollection mc = new ClipCollection();
                    mc.ClipLength = base.AppSettings.DefaultClipLength;
                    mc.Name = ci.Name;
                    mc.Items.Add(ci);

                    ArrayListDataSet toPlay = new ArrayListDataSet();
                    foreach (MediaMetaData item in ci.MediaItems)
                    {
                        toPlay.Add(item);
                    }
                    cb.VideoMetaData.Options = toPlay;
                    cb.CurrentChannel = mc;

                    ArrayListDataSet temp = new ArrayListDataSet();
                    temp.Add(mc);
                    cb.ToplineChoices.Options = temp;
                    cb.ClipSessionTitle = String.Format("{0} {1}", base.MonthConvert(ci.TimelineMonth), ci.TimelineYear);
                    cb.PlayClip();
                }
                catch (SystemException se)
                {
                    base.ShowDialog("clipShow exception", se.Message, true);
                }
                return (cb);

            }
        }
        public MainCodeBehind ResultPageWithChannel
        {
            get
            {
                PreviewChannelItem ci = (PreviewChannelItem)base.MediaLibraryItems.Options[base.CurrentTileIndex];
                MainCodeBehind cb = new MainCodeBehind();

                #region myClips only
                if (base.CurrentView.Equals(TileViewTypes.Playlists))
                {
                    Storage st = new Storage();
                    ClipCollection mc = st.GetClipCollection(ci.MediaChannelUri);
                    ClipItem ci2 = (ClipItem)mc.Items[0];
                    ArrayListDataSet tempResults = new ArrayListDataSet();
                    foreach (MediaMetaData med in ci2.MediaItems)
                    {
                        med.Thumbnail = new Image(BuildImagePath(med.ThumbnailUrl));
                        tempResults.Add(med);
                    }
                    cb.VideoMetaData.Options = tempResults;
                    ArrayListDataSet temp = new ArrayListDataSet();
                    temp.Add(mc);
                    cb.ToplineChoices.Options = temp;
                    cb.CurrentChannel = mc;
                    cb.ClipSessionTitle = ci.Name;
                    cb.PlayClip();
                }
                #endregion
                #region Snagged items
                else if (base.CurrentView.Equals(TileViewTypes.Snags))
                {
                    ClipCollection mc = new ClipCollection();
                    mc.ClipLength = base.AppSettings.DefaultClipLength;
                    mc.Name = ci.Name;
                    mc.Items.Add(ci);
                    if (ci.Name.Equals("All snags"))
                    {
                        cb.VideoMetaData.Options = cb.BuildChannelAllSnags();
                    }
                    else 
                    {
                        MediaMetaData parent = (MediaMetaData)ci.MediaItems[0];
                        cb.VideoMetaData.Options = cb.BuildChannelFromSnags(parent);
                    }
                    ArrayListDataSet temp = new ArrayListDataSet();
                    temp.Add(mc);
                    cb.ToplineChoices.Options = temp;
                    cb.CurrentChannel = mc;
                    cb.ClipSessionTitle = ci.Name;
                    cb.PlayClip();
                }
                #endregion
                else if(this.CurrentView.Equals(TileViewTypes.MediaItems)) 
                {
                    try
                    {
                        ClipCollection mc = new ClipCollection();
                        mc.ClipLength = base.AppSettings.DefaultClipLength;
                        mc.Name = ci.Name;
                        mc.Items.Add(ci);

                        cb.VideoMetaData.Options = cb.BuildChannelFromAll(ci.Keywords, base.MediaLibraries);
                        cb.CurrentChannel = mc;

                        if (ci.Keywords.Equals("ALL"))
                        {
                            ArrayListDataSet tempChannels = new ArrayListDataSet();
                            foreach (ClipItem ci2 in base.MediaLibraryItems.Options)
                            {
                                tempChannels.Add(ci2);
                            }

                            cb.ToplineChoices.Options = tempChannels;
                        }
                        else
                        {
                            ArrayListDataSet temp = new ArrayListDataSet();
                            temp.Add(mc);
                            cb.ToplineChoices.Options = temp;
                        }
                        cb.ClipSessionTitle = ci.Name;
                        cb.PlayClip();
                    }
                    catch (SystemException se)
                    {
                        base.ShowDialog("clipShow exception", se.Message, true);
                    }
                }
                return (cb);
            }
        }
        public bool CheckForLibraries
        {
            get
            {
                return (_haveLibraries);
            }
        }

        public void ShutDown()
        {
            AddInHost.Current.MediaCenterEnvironment.Dialog("You must first use the clipShow playlist creator to create a playlist.",
                "Missing playlist", Microsoft.MediaCenter.DialogButtons.Ok, 30000, true);
            AddInHost.Current.ApplicationContext.CloseApplication();
        }

        public bool TagsExist
        {
            get
            {
                long maxItems = 0;
                // First get the maxitems in all the media
                foreach (ClipShowContent cm in this.MediaLibraries.Options)
                {
                    if (!cm.ContentSourceName.Equals("my playlists"))
                    {
                        foreach (ClipItem ci in cm.KeywordItems)
                        {
                            if (!ci.Keywords.Equals("ALL"))
                            {
                                maxItems += ci.Count;
                            }
                        }
                    }
                }

                return (maxItems > 0);
            }
        }
        #endregion

        //#region Tag building private functions
        //private bool CheckForDuplicate(ArrayListDataSet source, PreviewChannelItem pci)
        //{
        //    bool result = false;
        //    foreach (PreviewChannelItem pciItem in source)
        //    {
        //        if (pciItem.Keywords.Equals(pci.Keywords))
        //        {
        //            pciItem.Count += pci.Count;
        //            result = true;
        //            break;
        //        }
        //    }
        //    return (result);
        //}
        //#endregion

        public MainCodeBehind ResultPageWithChannelFromTag
        {
            get
            {
                PreviewChannelItem pci = (PreviewChannelItem)base.MediaLibraryItems.Options[base.CurrentTileIndex];

                ClipCollection mc = new ClipCollection();
                mc.ClipLength = base.AppSettings.DefaultClipLength;
                mc.Name = pci.Name;
                mc.Items.Add(pci);

                MainCodeBehind cb = new MainCodeBehind();
                ArrayListDataSet tempResults = new ArrayListDataSet();
                cb.VideoMetaData.Options = cb.BuildChannelFromAll(pci.Keywords, base.MediaLibraries);
                cb.CurrentChannel = mc;

                ArrayListDataSet temp = new ArrayListDataSet();
                temp.Add(mc);

                cb.ToplineChoices.Options = temp;
                cb.ClipSessionTitle = pci.Name;
                cb.PlayClip();
                return (cb);
            }
        }

        public ChannelBuilderCodeBehind ResultPageForChannelBuilder
        {
            get
            {
                ChannelBuilderCodeBehind cbcb = new ChannelBuilderCodeBehind();
                return (cbcb);
            }
        }

        private ArrayList _thumbFlips = new ArrayList();
        private int _thumbFlipIndex = 0;
        public Image FlipThumb
        {
            get
            {
                _thumbFlipIndex++;
                if (_thumbFlipIndex == _thumbFlips.Count)
                {
                    _thumbFlipIndex = 1;
                }
                try
                {
                    string thumbUrl = BuildImagePath((string)_thumbFlips[_thumbFlipIndex]);
                    if(thumbUrl.StartsWith("resx"))
                    {
                        return((Image)_thumbFlips[0]);
                    }
                    else
                    {
                        Image im = new Image(thumbUrl);
                        return (im);
                    }
                }
                catch
                {
                    return ((Image)_thumbFlips[0]);
                }
            }
        }

        public void BuildThumbList(PreviewChannelItem item)
        {
            _thumbFlips.Clear();
            
            // Add current preview item thumb nail first
            _thumbFlips.Add(item.Thumbnail);
            _thumbFlipIndex = 1;

            if (this.CurrentView.Equals(TileViewTypes.Snags))
            {
                Storage st = new Storage();
                ArrayListDataSet tempResults = new ArrayListDataSet();
                ClipShowContent cm = st.GetSnagCollection();
                if (item.Keywords.Equals("ALL"))
                {
                    foreach (MediaMetaData ci in cm.MediaItems)
                    {
                        foreach (SnagItem si in ci.SnagList)
                        {
                            _thumbFlips.Add(si.ThumbnailUrl);
                        }
                    }
                }
                else
                {
                    foreach (MediaMetaData ci in cm.MediaItems)
                    {
                        if (item.Name.Equals(ci.Title))
                        {
                            _thumbFlips.Add(ci.ThumbnailUrl);
                            foreach (SnagItem si in ci.SnagList)
                            {
                                _thumbFlips.Add(si.ThumbnailUrl);
                            }
                            break;
                        }
                    }
                }
            }

            if (this.CurrentView.Equals(TileViewTypes.Playlists))
            {
                Storage st = new Storage();
                foreach (ClipCollection mc in st.GetMyCollections())
                {
                    if (mc.Name.Equals(item.Name))
                    {
                        ClipItem ci = (ClipItem)mc.Items[0];
                        foreach (MediaMetaData med in ci.MediaItems)
                        {
                            _thumbFlips.Add(med.ThumbnailUrl);
                        }
                        break;
                    }
                }
            }

            if (this.CurrentView.Equals(TileViewTypes.Timeline))
            {
                foreach (MediaMetaData s in item.MediaItems)
                {
                    _thumbFlips.Add(s.ThumbnailUrl);
                }
            }

            if (this.CurrentView.Equals(TileViewTypes.MediaItems))
            {
                string keyWords = item.Keywords;
                foreach (ClipShowContent mc2 in base.MediaLibraries.Options)
                {
                    foreach (MediaMetaData s in mc2.MediaItems)
                    {
                        if (!s.Title.Equals("N/A"))
                        {
                            if (keyWords.Equals("ALL"))
                            {
                                _thumbFlips.Add(s.ThumbnailUrl);
                            }
                            else
                            {
                                string[] keywords = keyWords.Split(';');
                                foreach (string keyword in keywords)
                                {
                                    if (base.CheckForKeyword(s, keyword))
                                    {
                                        if (!_thumbFlips.Contains(s.ThumbnailUrl))
                                        {
                                            _thumbFlips.Add(s.ThumbnailUrl);
                                        }
                                        break;
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
        public string AboutText
        {
            get
            {
                StringBuilder result = new StringBuilder();
                result.AppendFormat("clipShow version 1.0.921 (Beta 2)\n");
                return (result.ToString());
            }
        }

    }
}
